package p1;
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-09-16
 * Time: 11:41
 */

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * UDP 回显服务器,服务端
 */
public class UDPEchoServer {
    public DatagramSocket socket = null;

    //构造方法
    public UDPEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    //启动服务器
    public void start() throws IOException {

        System.out.println("服务器启动!!!");
        byte[] bytes = new byte[1024];


        while (true) {
            DatagramPacket packet = new DatagramPacket(bytes, 1024);

            //接收请求
            socket.receive(packet);
            String request = new String(packet.getData());


            //根据请求计算响应
            String response = process(request);

            //返回响应
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), 1024,
                    packet.getSocketAddress());

            socket.send(responsePacket);

        }

    }

    public String process(String s) {
        return s;
    }

    public static void main(String[] args) {

    }
}
